package com.my12306.user.service.auth.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.my12306.common.enums.CodeEnum;
import com.my12306.common.util.PageUtils;
import com.my12306.common.util.SnowflakeIdWorker;
import com.my12306.common.util.response.ResponseData;
import com.my12306.user.dao.auth.RoleDao;
import com.my12306.user.model.po.auth.RoleEntity;
import com.my12306.user.model.po.auth.RolePermissionEntity;
import com.my12306.user.model.vo.RoleVo;
import com.my12306.user.service.auth.RolePermissionService;
import com.my12306.user.service.auth.RoleService;
import com.my12306.user.service.auth.UserRoleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.my12306.common.util.CommentUtils.getPoToVo;


@Service("roleService")

public class RoleServiceImpl extends ServiceImpl<RoleDao, RoleEntity> implements RoleService {
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RolePermissionService rolePermissionService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String roleName = (String) params.get("roleName");
        System.out.println(roleName);
        QueryWrapper<RoleEntity> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(roleName)) {
            wrapper.or().like("role_name", roleName).or().like("role_desc", roleName);
        }
        Integer page = Integer.parseInt(params.get("page").toString());
        Integer limit = Integer.parseInt(params.get("limit").toString());
        if (page != null && page < 1) {
            page = 1;
            limit = 10;
        }
        IPage<RoleEntity> iPage = new Page(page, limit);
        IPage<RoleEntity> pg = this.page(
                iPage,
                wrapper
        );
        return new PageUtils(pg);
    }


    @Override
    public List<RoleEntity> selectAllRole() {
        return this.baseMapper.selectList(null);
    }

    @Override
    public ResponseData updateRoleById(RoleEntity roleEntity) {
        int i = this.baseMapper.updateById(roleEntity);
        if (i > 0) {
            return ResponseData.ok();
        }
        return ResponseData.fail(CodeEnum.UPDATE_FAIL.getCode(), CodeEnum.UPDATE_FAIL.getMessage());
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData deleteBatchByIds(List<Long> ids) {
        //批量删除角色
        this.baseMapper.deleteBatchIds(ids);
        //批量生产用户和角色
        userRoleService.deleteUserRoleByRoleIds(ids);
        //删除角色和权限关系
        rolePermissionService.deleteRolePermissionByRoleIds(ids);
        return ResponseData.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_UNCOMMITTED)
    public Boolean saveRoleAndPerms(RoleVo roleVo) {
        if (roleVo == null) return false;
        List<Long> permIds = roleVo.getMenuIdList();
        RoleEntity roleEntity = new RoleEntity();
        getPoToVo(roleVo, roleEntity);
        roleEntity.setCreateDate(new Date());
        roleEntity.setUpdateDate(new Date());
        roleEntity.setRoleId(SnowflakeIdWorker.generateId());
        //添加角色
        this.baseMapper.insert(roleEntity);

        System.out.println(roleEntity);
        //如果权限不为空,则添加权限
        if (permIds != null) {
            System.out.println("ids=" + permIds);
            List<RolePermissionEntity> rolePerms = createRolePerms(roleEntity.getRoleId(), permIds);
            System.out.println("role-permission=================>");
            System.out.println(rolePerms);
            rolePermissionService.saveBatchRolePerms(rolePerms);
            return true;
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBatchRoleAndPerms(RoleVo roleVo) {
        List<Long> menuIdList = roleVo.getMenuIdList();
        RoleEntity roleEntity = new RoleEntity();
        getPoToVo(roleVo, roleEntity);
        roleEntity.setUpdateDate(new Date());
        //组装新的权限
        List<RolePermissionEntity> rolePerms = createRolePerms(roleEntity.getRoleId(), menuIdList);
        //删除旧角色-权限
        rolePermissionService.deleteRolePermissionByRoleIds(Arrays.asList(roleEntity.getRoleId()));
        //添加新权限
        rolePermissionService.saveBatchRolePerms(rolePerms);
        //修改角色
        this.baseMapper.updateById(roleEntity);
        return;
    }

    @Override
    public Long queryRoleIdByRoleName(String user_role) {
        if (user_role != null) {
            RoleEntity role_name = this.baseMapper.selectOne(new QueryWrapper<RoleEntity>().eq("role_name", user_role));
            return role_name == null ? null : role_name.getRoleId();
        }
        return null;
    }

    //组装Bean
    public List<RolePermissionEntity> createRolePerms(Long roleId, List<Long> permIds) {
        List<RolePermissionEntity> rolePermList = permIds.stream().parallel().map(x -> {
            RolePermissionEntity rolePermissionEntity = new RolePermissionEntity();
            rolePermissionEntity.setRoleId(roleId);
            rolePermissionEntity.setPermId(x);
            rolePermissionEntity.setCreateDate(new Date());
            rolePermissionEntity.setUpdateDate(new Date());
            return rolePermissionEntity;
        }).collect(Collectors.toList());
        return rolePermList;
    }

}
